﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using ARchGL.Platform.Authorization.Users;
using ARchGL.Platform.Electrocar.Application.Dto;
using ARchGL.Platform.Electrocar.Core;
using ARchGL.Platform.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ARchGL.Platform.Electrocar.Application
{
    /// <summary>
    /// 厂家服务 实现
    /// </summary>
    public class CompanysAppService : BaseService
    {
        private readonly IRepository<Companys, Guid> companysRepository;

        private readonly UserManager userManager;

        public CompanysAppService(
            IRepository<Companys, Guid> _companysRepository,
            UserManager _userManager)
        {
            companysRepository = _companysRepository;
            userManager = _userManager;
        }

        /// <summary>
        /// 创建/编辑厂家
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrModifyCompany(CompanysDto input)
        {
            if (input.Id == Guid.Empty)
            {
                var entity = ObjectMapper.Map<Companys>(input);
                await companysRepository.InsertAsync(entity);
            }
        }

        /// <summary>
        /// 删除厂家
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task RemoveCompany(EntityDto<Guid> input)
        {
            var entity = await companysRepository.GetAsync(input.Id);
            if (entity == null) throw new UserFriendlyException("公司不存在，请重新输入");
            await companysRepository.DeleteAsync(entity);
        }

        /// <summary>
        /// 获取厂家信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CompanysDto> QueryCompanyById(EntityDto<Guid> input)
        {
            var entity = await companysRepository.GetAsync(input.Id);
            return ObjectMapper.Map<CompanysDto>(entity);
        }

        /// <summary>
        /// 获取厂家-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CompanysDto>> QueryCompanyPagedList(CompanysInput input)
        {
            var query = companysRepository.GetAll()
                    .WhereIf(!input.Keywords.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Keywords) || x.Address.Contains(input.Keywords) || x.Telephone.Contains(input.Keywords));

            var result = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<CompanysDto>(query.Count(),
                ObjectMapper.Map<List<CompanysDto>>(query));
        }
    }
}
